package android.contest.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.contest.R;
import android.contest.alarmclock.AlarmAlertWakeLock;
import android.contest.alarmclock.AlarmMgr;
import android.contest.db.AlarmDBMgr;
import android.contest.util.Log;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

public class NotifyActivity extends Activity{
	public static String EXTRA_ITEM = "EXTRA_ITEM", EXTRA_STEP = "EXTRA_STEP", 
			EXTRA_CHOICE = "EXTRA_CHOICE", EXTRA_TIME="EXTRA_TIME", EXTRA_STEP_TIME="EXTRA_STEP_TIME";
	private long m_itemId, m_latest_alarm_time, m_nextstep_time;
	private int m_stepId;
	private boolean m_hasNegativeChoice;
	private Ringtone m_ringtone;
	private 
	DialogInterface.OnClickListener m_positiveListener;
	private 
	DialogInterface.OnClickListener m_negativeListener;
	private OnCancelListener m_onCancelListener;
	private String m_timeHasPassed;
    private KeyguardManager mKeyguardManager;
    private KeyguardManager.KeyguardLock mKeyguardLock;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
				
		Intent intent = getIntent();
		m_itemId = intent.getLongExtra(EXTRA_ITEM, -1);
		m_stepId = intent.getIntExtra(EXTRA_STEP, -1);
		m_hasNegativeChoice = intent.getBooleanExtra(EXTRA_CHOICE, false);
		m_latest_alarm_time = intent.getLongExtra(EXTRA_TIME, -1);
		m_nextstep_time = intent.getLongExtra(EXTRA_STEP_TIME, -1);
		
		m_timeHasPassed = getResources().getString(R.string.time_has_passed);		

		mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
		
		System.out.println("itemId = " + m_itemId + ", stepId = " + m_stepId + "hasNegativeChoice " + m_hasNegativeChoice);
		
		m_positiveListener = new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					AlarmMgr.updateAlertedAlarm2(m_latest_alarm_time, m_itemId);
					if(m_ringtone != null) m_ringtone.stop();
					NotifyActivity.this.finish();
				}
			};
			
		m_onCancelListener = new OnCancelListener() {
			public void onCancel(DialogInterface arg0) {
				AlarmMgr.updateAlertedAlarm2(m_latest_alarm_time, m_itemId);
				if(m_ringtone != null) m_ringtone.stop();
				NotifyActivity.this.finish();
			}
		};
		
		m_negativeListener = new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(m_nextstep_time != -1 && m_nextstep_time < System.currentTimeMillis())
				{
					Toast.makeText(getApplicationContext(), m_timeHasPassed, Toast.LENGTH_LONG);
					Log.v(Log.LOGDB, "m_negativeListener: m_nextstep_time < System.currentTimeMillis()");
					AlarmMgr.updateAlertedAlarm2(m_latest_alarm_time, m_itemId);
				}
				else{
				//Push all alarms contained to the next epochs as only the first alarm has this privilege
				if(!AlarmMgr.scheduleNextEpoch2(m_itemId))
					Log.v(Log.LOGDB, "AlarmMgr.scheduleNextEpoch2: false");
				else
					AlarmMgr.setNextAlert(getApplicationContext());
				}
				if(m_ringtone != null) m_ringtone.stop();		    	
		    	NotifyActivity.this.finish();
			}
		};
		
		String preferencesFileName = TaskListView.PREFIX_PREFERENCES_FILE_NAME + ((Long)m_itemId).toString();
		SharedPreferences preferences = this.getSharedPreferences(preferencesFileName, Activity.MODE_PRIVATE);
		if(preferences != null)
		{
			String prefix = "step", suffix = "_description";
			String stepi_desKey = prefix + ((Integer)m_stepId) + suffix;
			String notify_info = this.getResources().getString(R.string.notify_info_head)
					+ " " +  preferences.getString(stepi_desKey, "")
					+ this.getResources().getString(R.string.notify_info_tail);
						
			AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
			alertBuilder.setIcon(R.drawable.ic_menu_clock);  
			alertBuilder.setTitle(this.getResources().getString(R.string.notify_title));  
			alertBuilder.setMessage(notify_info);  
			alertBuilder.setPositiveButton(this.getResources().getString(R.string.yes),  m_positiveListener);
			alertBuilder.setOnCancelListener(m_onCancelListener);
			if(m_hasNegativeChoice)
				alertBuilder.setNegativeButton(this.getResources().getString(R.string.no),  m_negativeListener);		
			alertBuilder.show();

			String ringtoneKey = getResources().getString(R.string.ringtone);
			String ringtoneSaved = preferences.getString(ringtoneKey, null); 
			if(!ringtoneSaved.contentEquals("")){
			   Uri ringtoneUri = Uri.parse(ringtoneSaved);
			   m_ringtone = RingtoneManager.getRingtone(this, ringtoneUri);
			   if(m_ringtone != null ) m_ringtone.play();
			}	
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		this.disableKeyguard();
	}



	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		this.enableKeyguard();
	}

	private synchronized void enableKeyguard() {
	    if (mKeyguardLock != null) {
	        mKeyguardLock.reenableKeyguard();
	        mKeyguardLock = null;
	    }
	}

	private synchronized void disableKeyguard() {
	    if (mKeyguardLock == null) {
	        mKeyguardLock = mKeyguardManager.newKeyguardLock("LaundryReminder");
	        mKeyguardLock.disableKeyguard();
	    }
	    }

//	public static void notifyLaundry(Context context, long itemId, int stepId, boolean hasNegativeChoice,
//			DialogInterface.OnClickListener positiveListener, DialogInterface.OnClickListener negativeListener,
//			OnCancelListener onCancelListener){
//		String preferencesFileName = TaskListView.PREFIX_PREFERENCES_FILE_NAME + ((Long)itemId).toString();
//		SharedPreferences preferences = context.getSharedPreferences(preferencesFileName, Activity.MODE_PRIVATE);
//		if(preferences != null)
//		{
//			String prefix = "step", suffix = "_description";
//			String stepi_desKey = prefix + ((Integer)stepId) + suffix;
//			String notify_info = context.getResources().getString(R.string.notify_info_head)
//					+ " " +  preferences.getString(stepi_desKey, "")
//					+ context.getResources().getString(R.string.notify_info_tail);
//						
//			AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
//			alertBuilder.setIcon(R.drawable.ic_menu_clock);  
//			alertBuilder.setTitle(context.getResources().getString(R.string.notify_title));  
//			alertBuilder.setMessage(notify_info);  
//			alertBuilder.setPositiveButton(context.getResources().getString(R.string.yes),  positiveListener);
//			alertBuilder.setOnCancelListener(onCancelListener);
//			if(hasNegativeChoice)
//				alertBuilder.setNegativeButton(context.getResources().getString(R.string.no),  negativeListener);
//			
////			alertBuilder.show();  
//			AlertDialog alertDialog = alertBuilder.create();
//			LayoutParams params = alertDialog.getWindow().getAttributes();
//			params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
//			params.token = null;			
//			alertDialog.getWindow().setAttributes(params);
//			alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//			alertDialog.show();
//		}
//	}
}
